<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\Base\Command\Traits\KfGetTimeInterval;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Order\Model\OrderAbnormalityModel;
use App\Kuafu\Order\Model\OrderStatisticalModel;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiCallbackLogModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WaiMaiBatchQueryExec extends Command
{
    use KfGetTimeInterval;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waimai:batch-query-exec {--d=false :  是否直接执行 示例.true - 默认执行前一天数据 false - 交互式执行} {--debug=false}';

    /**ø
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖全量查询数据库';

    private bool $isStoreDb = true; // 受 debug 影响 && 是否入库

    private array $orderShopList = [];

    private array $num = [
        'errorNum' => 0,   // 异常订单总量
        'totalNum' => 0,   // 总订单量
        'shopNum'  => 0,   // 在线店铺数量

        'offlineTotalNum' => 0, // 离线订单总量
        'offlineShopNum'  => 0, // 离线门店数量
    ];

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        @ini_set('memory_limit', '-1');
        $this->debug        = $this->option('debug') == 'true';
        $this->debugShopId  = [12018, 13112];
        $this->debugOrderId = [];


        $skipShopList = [13315]; // 跳过的 店铺id
        if ($this->debug) {
            list($startTimeAt, $endTimeAt) = [
                strtotime('2023-01-01 00:00:00'),
                strtotime('2023-01-05 00:00:00')
            ]; // 2022-01-01 - time()
        } else {
            list($startTimeAt, $endTimeAt) = $this->getTimeInterval();
        }

        $this->info('**************** 开始执行脚本 ****************');
        $this->info(vsprintf(
            '起始时间 [ %s ] 截止时间 [ %s ]',
            [date('Y-m-d H:i:s', $startTimeAt), date('Y-m-d H:i:s', $endTimeAt)]
        ));

        $initArr = [];
        if ($this->debug && !empty($this->debugShopId)) {
            $initArr = $this->debugShopId;
        } else {
            for ($i = 0; $i <= 99; $i++) {
                $initArr[] = $i;
            }
        }

        // 获取以下内容的订单
        foreach ($initArr as $i) {
            $this->errorOrder = []; // 重置

            // 为payStreamRel服务
            (new BaseModel())->setSplitShopId($i);

            WaiMaiOrderModel::suffix($i)
                            ->where('orderStatus', '!=', WaiMaiDBEnum::ORDER_STATUS_7)
                            ->whereBetween('createdAt', [$startTimeAt, $endTimeAt])
                            ->chunk(500, function ($wmOrder) {
                                foreach ($wmOrder as $order) {
                                    /* 数据统计 */
                                    $this->handleShop($order);
                                    /* 数据统计 */
                                }
                            });

            $this->info('当前循环表 :' . $i);
            $this->insertStatisticalDb();
        }
    }

    private function handleShop($order)
    {
        $time = date('Y-m-d', $order->createdAt->getTimestamp());
        if (empty($this->orderShopList[$order->shopId][$time])) {

            $this->orderShopList[$order->shopId][$time] = [
                'orderNum'        => 0, // 订单量
                'offlineOrderNum' => 0, // 离线订单量
                'shopId'          => $order->shopId, // shopId
                'originalPrice'   => 0, // 订单原价
                'discountPrice'   => 0, // 订单优惠
                'payPrice'        => 0, // 订单实付
                'realPayPrice'    => 0, // 商家实收
                'time'            => strtotime($time)
            ];
        }

        $this->orderShopList[$order->shopId][$time]['orderNum']++;

        // 统计订单数据
        $this->orderShopList[$order->shopId][$time]['originalPrice'] += $order->originalPrice;
        $this->orderShopList[$order->shopId][$time]['payPrice']      += $order->payPrice;
        $this->orderShopList[$order->shopId][$time]['realPayPrice']  += $order->expectIncome;
        $this->orderShopList[$order->shopId][$time]['discountPrice'] =
            $this->orderShopList[$order->shopId][$time]['originalPrice'] - $this->orderShopList[$order->shopId][$time]['payPrice'];

    }

    private function insertStatisticalDb()
    {
        $insertData = [];
        foreach ($this->orderShopList as $timeList) {
            foreach ($timeList as $time => $item) {
                $insertData[] = [
                    'shopId'        => $item['shopId'],
                    'offNum'        => $item['offlineOrderNum'],
                    'num'           => $item['orderNum'],
                    'originalPrice' => $item['originalPrice'],
                    'discountPrice' => $item['discountPrice'],
                    'payPrice'      => $item['payPrice'],
                    'realPayPrice'  => $item['realPayPrice'],
                    'time'          => strtotime($time),
                    'type'          => 2
                ];
            }
        }

        OrderStatisticalModel::query()
                             ->whereIn('shopId', array_column($insertData, 'shopId'))
                             ->whereIn('time', array_column($insertData, 'time'))
                             ->where('type', 2)
                             ->delete();

        if ($this->debug === false && $this->isStoreDb === true) {
            collect($insertData)->chunk(500)->each(function ($item) {
                OrderStatisticalModel::query()->insert($item->toArray());
            });
        }

    }

}
